package com.uy.cuantoconocesdeuruguay.adapters;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.uy.cuantoconocesdeuruguay.FriendChallenge;
import com.uy.cuantoconocesdeuruguay.MainActivity;
import com.uy.cuantoconocesdeuruguay.MyChallenges;
import com.uy.cuantoconocesdeuruguay.R;
import com.uy.cuantoconocesdeuruguay.animations.HeightResizeAnimation;
import com.uy.cuantoconocesdeuruguay.animations.WidthResizeAnimation;
import com.uy.cuantoconocesdeuruguay.datatypes.FacebookUser;
import com.uy.cuantoconocesdeuruguay.datatypes.FriendChallengeEnvelope;
import com.uy.cuantoconocesdeuruguay.dialogs.ChallengeFinishedDialogUtils;
import com.uy.cuantoconocesdeuruguay.dialogs.ChallengeWaitingForOponentDialogUtils;
import com.uy.cuantoconocesdeuruguay.dialogs.ErrorOccurredDialogUtils;
import com.uy.cuantoconocesdeuruguay.exceptions.ConnectivityException;
import com.uy.cuantoconocesdeuruguay.listeners.SwipeTouchListener;
import com.uy.cuantoconocesdeuruguay.server.ServerConnector;
import com.uy.cuantoconocesdeuruguay.utiles.ImageLoader;
import com.uy.cuantoconocesdeuruguay.utiles.MetricsUtiles;
import com.uy.cuantoconocesdeuruguay.utiles.StringPool;
import com.uy.cuantoconocesdeuruguay.utiles.SystemConstants;

public class MyChallengesViewAdapter extends ArrayAdapter<FriendChallengeEnvelope> {
    private static final int RED = Color.argb(238, 230, 86, 64);
    private static final int GREEN = Color.argb(238, 97, 174, 36);
    private static final int YELLOW = Color.argb(238, 241, 141, 5);
    private static final int GRAY = Color.argb(238, 184, 184, 184);
    private static final int OVERLAY = Color.argb(51, 255, 255, 255);

    private MyChallenges activity;
    private List<FriendChallengeEnvelope> challenges;
    private int px60;
    private int px1;
    
	public MyChallengesViewAdapter(MyChallenges activity, String[] items, List<FriendChallengeEnvelope> challenges) {
		super(activity.getApplicationContext(), R.layout.activity_my_challenges, challenges);
		this.activity = activity;
		this.challenges = challenges;
		px1 = (int) MetricsUtiles.convertDpToPixel(1, activity);
		px60 = (int) MetricsUtiles.convertDpToPixel(60, activity);
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewHolder viewHolder = null;
		if (convertView == null) {
		    LayoutInflater inflater = (LayoutInflater) activity.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		    convertView = inflater.inflate(R.layout.view_challenges, parent, false);		    
		    viewHolder = new ViewHolder();
		    viewHolder.challengeView = convertView;
		    viewHolder.layoutFriendView = (LinearLayout) convertView.findViewById(R.id.layout_friend_view);
		    viewHolder.layoutBg = (LinearLayout) convertView.findViewById(R.id.layout_friend_view_bg);
		    viewHolder.layoutOverlay = (RelativeLayout) convertView.findViewById(R.id.layout_friend_view_overlay);
		    viewHolder.actionIcon = (ImageView) convertView.findViewById(R.id.actionIcon);
		    viewHolder.friendName = (TextView)convertView.findViewById(R.id.friendName);
		    viewHolder.challengeStart = ((TextView) convertView.findViewById(R.id.challengeStart));
		    viewHolder.challengeExpires = ((TextView) convertView.findViewById(R.id.challengeExpires));
		    viewHolder.imgViewer = (ImageView) convertView.findViewById(R.id.friendImage);
		    viewHolder.loader = (ProgressBar)convertView.findViewById(R.id.challengeListLoader);
		    viewHolder.revengeImageLayout = (LinearLayout)convertView.findViewById(R.id.friendRevengeImageLayout);
		    viewHolder.deleteImageLayout = (LinearLayout)convertView.findViewById(R.id.friendDeleteImageLayout);
            convertView.setTag(viewHolder);
        } else { 
            viewHolder = (ViewHolder) convertView.getTag();
        }
		viewHolder.loader.setVisibility(View.VISIBLE);
		viewHolder.imgViewer.setImageResource(R.drawable.com_facebook_profile_default_icon);
		viewHolder.layoutOverlay.setBackgroundColor(OVERLAY);
	    final ViewHolder viewHolderFinal = viewHolder;

	    LayoutParams challengeViewLayoutParams =  viewHolderFinal.challengeView.getLayoutParams();
	    challengeViewLayoutParams.height = LayoutParams.WRAP_CONTENT;
	    challengeViewLayoutParams.width = LayoutParams.MATCH_PARENT;
	    viewHolderFinal.challengeView.setLayoutParams(challengeViewLayoutParams);
	    
	    final FriendChallengeEnvelope challenge = challenges.get(position);
	    final FacebookUser oponent = challenge.getOponent();
	    final boolean proposedByMe = challenge.getProposerFacebookId().equals(MainActivity.userData.getFacebookid());
	    String time = StringPool.BLANK;
	    long timeProposed = SystemConstants.getTime() - challenge.getChallengeCreated();
	    long timeElapsed;
	    if (proposedByMe){
	    	if (challenge.getChallengeStartProposer() == 0){
	    		timeElapsed = 0;
	    	}else{
	    		timeElapsed = SystemConstants.getTime() - challenge.getChallengeStartProposer();
	    	}
	    }else{
	    	if (challenge.getChallengeStartOponent() == 0){
	    		timeElapsed = 0;
	    	}else{
	    		timeElapsed = SystemConstants.getTime() - challenge.getChallengeStartOponent();
	    	}
	    }
	    int minutos = 	(int) (timeElapsed/60000);
	    int horas = 	minutos/60;
	    int dias = 		horas/24;
	    if ( dias > 0){
	    	time = dias+ (dias > 1 ? activity.getString(R.string.days_ago) : activity.getString(R.string.day_ago));
	    }else if (horas > 0){
	    	time = horas + (horas > 1 ? activity.getString(R.string.hours_ago) : activity.getString(R.string.hour_ago));
	    }else if ( minutos > 0){
	    	time = minutos + (minutos > 1 ? activity.getString(R.string.minutes_ago) : activity.getString(R.string.minute_ago));
	    }else{
	    	time = activity.getString(R.string.moment_ago);
	    }
	    viewHolderFinal.challengeExpires.setText(StringPool.BLANK);
	    viewHolderFinal.layoutBg.setBackgroundColor(YELLOW);
	    viewHolderFinal.revengeImageLayout.setBackgroundColor(YELLOW);
		viewHolderFinal.deleteImageLayout.setBackgroundColor(YELLOW);
	    viewHolderFinal.actionIcon.setImageResource(R.drawable.comment);
	    OnClickListener challengeOnClickListener;
	    boolean challengeTimedOut = false;
	    if (challenge.isFinished()){
	    	setChallengeFinalScoreText(viewHolderFinal, challenge, proposedByMe);
	    	challengeOnClickListener = new OnClickListener() {				
				@Override
				public void onClick(View v) {
					ChallengeFinishedDialogUtils dialogUtils = new ChallengeFinishedDialogUtils(activity);
					dialogUtils.createChallengeFinishedPopup(challenge,true);
				}
			};
	    }else{ 
		    challengeTimedOut = (
	    		(challenge.isAccepted() && (timeElapsed >= SystemConstants.CHALLENGE_MAX_PLAY_TIME || timeProposed >= SystemConstants.CHALLENGE_MAX_WAIT_TIME)) || 
	    		(!challenge.isAccepted() && timeProposed >= SystemConstants.CHALLENGE_MAX_WAIT_TIME)
	    	);
		    if (challengeTimedOut || oponent == null){
		    	challengeOnClickListener = new OnClickListener() {				
					@Override
					public void onClick(View v) {
						ChallengeFinishedDialogUtils dialogUtils = new ChallengeFinishedDialogUtils(activity);
						dialogUtils.createChallengeFinishedPopup(challenge,true);
					}
				};
	    		if (challenge.isAccepted()){
		    		setChallengeFinalScoreText(viewHolderFinal, challenge, proposedByMe);
	    		}else{
		    		viewHolderFinal.challengeStart.setText(activity.getString(R.string.my_challenges_view_adapter_time_up));
		    		viewHolderFinal.layoutBg.setBackgroundColor(GRAY);
		    		viewHolderFinal.revengeImageLayout.setBackgroundColor(GRAY);
		    		viewHolderFinal.deleteImageLayout.setBackgroundColor(GRAY);
		    		viewHolderFinal.challengeExpires.setText(StringPool.BLANK);
		    		viewHolderFinal.actionIcon.setImageResource(R.drawable.clock);
	    		}
		    }else if (imDoneChallenge(challenge)){
		    	challengeOnClickListener = new OnClickListener() {				
					@Override
					public void onClick(View v) {
						ChallengeWaitingForOponentDialogUtils dialogUtils = new ChallengeWaitingForOponentDialogUtils(activity);
						dialogUtils.createChallengeWaitingForOponentPopup(challenge,true);
						
					}
				};	
		    	viewHolderFinal.challengeStart.setText(activity.getString(R.string.my_challenges_view_adapter_waiting_for_oponent));
			}else{
				challengeOnClickListener = new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						if (challenge.isAccepted() || !proposedByMe){
							openChallenge(challenge, proposedByMe);
						}else{
							Toast.makeText(activity, activity.getString(R.string.my_challenges_view_adapter_not_yet_accepted), Toast.LENGTH_SHORT).show();
						}
					}
			    };
			    viewHolderFinal.actionIcon.setOnClickListener(challengeOnClickListener);

	    		long expiresIn;	    		
			    if (challenge.isAccepted()){
			    	viewHolderFinal.actionIcon.setImageResource(R.drawable.skip);
			    	if (proposedByMe && challenge.getChallengeStartProposer() == 0){
			    		viewHolderFinal.challengeStart.setText(activity.getString(R.string.my_challenges_view_adapter_start_now));	
			    		expiresIn = SystemConstants.CHALLENGE_MAX_WAIT_TIME - timeProposed;
			    	}else{
			    		viewHolderFinal.challengeStart.setText(activity.getString(R.string.my_challenges_view_adapter_started_ago)+time);
			    		expiresIn = SystemConstants.CHALLENGE_MAX_PLAY_TIME - timeElapsed;
			    	}
			    }else{
			    	if (proposedByMe){
				    	viewHolderFinal.actionIcon.setImageResource(R.drawable.comment);
				    	viewHolderFinal.challengeStart.setText(activity.getString(R.string.my_challenges_view_adapter_not_yet_accepted));
			    	}else{
				    	viewHolderFinal.actionIcon.setImageResource(R.drawable.accept);
			    		viewHolderFinal.challengeStart.setText(activity.getString(R.string.my_challenges_view_adapter_accept_challenge));	
			    	}
		    		expiresIn = SystemConstants.CHALLENGE_MAX_WAIT_TIME - timeProposed;
			    }
			    
	    		if (expiresIn> 0 ){
		    		int minutosExp = (int) (expiresIn/60000);
		    	    int horasExp = 	minutosExp/60;
		    	    int diasExp = 	horasExp/24;
		    	    String timeExp = StringPool.BLANK;
		    	    if ( diasExp > 0){
		    	    	timeExp = diasExp+ (diasExp > 1 ? activity.getString(R.string.days) : activity.getString(R.string.day));
		    	    }else if (horasExp > 0){
		    	    	timeExp = horasExp + (horasExp > 1 ? activity.getString(R.string.hours) : activity.getString(R.string.hour));
		    	    }else if ( minutosExp > 0){
		    	    	timeExp = minutosExp + (minutosExp > 1 ? activity.getString(R.string.minutes) : activity.getString(R.string.minute));
		    	    }else{
		    	    	timeExp = activity.getString(R.string.few_seconds);
		    	    } 
		    		viewHolderFinal.challengeExpires.setText(activity.getString(R.string.my_challenges_view_adapter_expires_in)+timeExp);
	    		}
		    }	
	    } 
	    if (oponent == null){
	    	viewHolderFinal.friendName.setText(activity.getString(R.string.my_challenges_view_adapter_friend_not_found));
	    	viewHolderFinal.loader.setVisibility(View.GONE);
	    }else{
	    	viewHolderFinal.friendName.setText(oponent.getFirst_name() + StringPool.SPACE + oponent.getLast_name());
	    	if ( !(oponent.getPicture() == null || oponent.getPicture().equals(StringPool.BLANK)) ){
	    		ImageLoader.loadImageOn(activity, viewHolderFinal.imgViewer, oponent.getPicture(), viewHolderFinal.loader);
	    	}
	    }
	    
	    
	    final OnClickListener challengeOnClickListenerFinal = challengeOnClickListener;
	    viewHolderFinal.deleteImageLayout.getLayoutParams().width = (challenge.isDeleteMark() ? px60 : px1);
	    viewHolderFinal.revengeImageLayout.getLayoutParams().width = (challenge.isRevengeMark() ? px60 : px1);
	    final boolean isSwipeEnabled = challengeTimedOut || challenge.isFinished();
    	viewHolderFinal.challengeView.setOnTouchListener(new SwipeTouchListener() {
	        public void onSwipeRight() {
	        	if (isSwipeEnabled){
		            if (viewHolderFinal.deleteImageLayout.getLayoutParams().width > px1){
		            	hideDelete(viewHolderFinal,challenge);
		            }else if (viewHolderFinal.revengeImageLayout.getLayoutParams().width == px1){
		            	showRevenge(viewHolderFinal,challenge);
		            }
	        	}
	        }
	        public void onSwipeLeft() {
	        	if (isSwipeEnabled){
		            if (viewHolderFinal.revengeImageLayout.getLayoutParams().width > px1){
		            	hideRevenge(viewHolderFinal,challenge);
		            }else if (viewHolderFinal.deleteImageLayout.getLayoutParams().width == px1){
		            	showDelete(viewHolderFinal,challenge);
		            }
	        	}
	        }
	        public void onTouchDown(){
	        	challengeOnClickListenerFinal.onClick(viewHolderFinal.challengeView);
	        }
	    });
	    viewHolderFinal.revengeImageLayout.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {	
				if (oponent == null){
					Toast.makeText(activity, activity.getString(R.string.my_challenges_view_adapter_revenge_not_available), Toast.LENGTH_SHORT).show();
				}else{
					String friendName = oponent.getFirst_name();
					String friendId = oponent.getId();
					FriendsViewAdapter.challengeFriend(friendName, friendId, null, activity);
				}
				hideRevenge(viewHolderFinal,challenge);
			} 
		});
	    viewHolderFinal.deleteImageLayout.setOnClickListener(new OnClickListener() {			
			@Override 
			public void onClick(View v) {
				try {
					ServerConnector.deleteChallenge(challenge.getId(), proposedByMe);
					viewHolderFinal.actionIcon.setImageDrawable(null);
					HeightResizeAnimation hideAnimation = new HeightResizeAnimation(viewHolderFinal.challengeView,true);
	            	hideAnimation.setParams(viewHolderFinal.challengeView.getHeight(), 1);
	            	hideAnimation.setFinishParameters(activity, challenges, position, MyChallengesViewAdapter.this);
	            	viewHolderFinal.challengeView.startAnimation(hideAnimation);
	            	hideDelete(viewHolderFinal,challenge);
				} catch (ConnectivityException e) {
					ErrorOccurredDialogUtils dialog = new ErrorOccurredDialogUtils(activity, e);
					dialog.createErrorOccurredPopup();
					e.printStackTrace();
				}
			}
		});
	    return convertView;
	}
	protected void showDelete(ViewHolder viewHolder, FriendChallengeEnvelope challenge) {
    	WidthResizeAnimation showAnimation = new WidthResizeAnimation(viewHolder.deleteImageLayout);
    	showAnimation.setParams(px1, px60);
    	viewHolder.deleteImageLayout.startAnimation(showAnimation);
    	challenge.setDeleteMark(true);
	}

	protected void hideRevenge(ViewHolder viewHolder, FriendChallengeEnvelope challenge) {
    	WidthResizeAnimation hideAnimation = new WidthResizeAnimation(viewHolder.revengeImageLayout);
    	hideAnimation.setParams(px60, px1);
    	viewHolder.revengeImageLayout.startAnimation(hideAnimation);
    	challenge.setRevengeMark(false);
	}

	protected void showRevenge(ViewHolder viewHolder, FriendChallengeEnvelope challenge) {
    	WidthResizeAnimation showAnimation = new WidthResizeAnimation(viewHolder.revengeImageLayout);
    	showAnimation.setParams(px1, px60);
    	viewHolder.revengeImageLayout.startAnimation(showAnimation);
    	challenge.setRevengeMark(true);
	}

	protected void hideDelete(ViewHolder viewHolder, FriendChallengeEnvelope challenge) {
    	WidthResizeAnimation hideAnimation = new WidthResizeAnimation(viewHolder.deleteImageLayout);
    	hideAnimation.setParams(px60, px1);
    	viewHolder.deleteImageLayout.startAnimation(hideAnimation);
    	challenge.setDeleteMark(false);
	}

	@Override
	public void remove(FriendChallengeEnvelope object) {
		super.remove(object);
		challenges.remove(object);
	}
	private void setChallengeFinalScoreText(ViewHolder viewHolder,FriendChallengeEnvelope challenge, boolean proposedByMe) {
		boolean win = false;
		View challengeView = viewHolder.layoutBg;
		TextView challengeStart = viewHolder.challengeStart;
		ImageView actionIcon = viewHolder.actionIcon;
		if (proposedByMe){
			if (challenge.getChallengeScoreProposer() > challenge.getChallengeScoreOponent()){
				win = true;
			}
		}else{
			if (challenge.getChallengeScoreOponent() >= challenge.getChallengeScoreProposer()){
				win = true;
			}
		}
		if (win){
			challengeStart.setText(activity.getString(R.string.my_challenges_view_adapter_won));
			challengeView.setBackgroundColor(GREEN);
			viewHolder.revengeImageLayout.setBackgroundColor(GREEN);
			viewHolder.deleteImageLayout.setBackgroundColor(GREEN);
			actionIcon.setImageResource(R.drawable.face_win);
		}else{
			challengeStart.setText(activity.getString(R.string.my_challenges_view_adapter_lose));
			challengeView.setBackgroundColor(RED);
			viewHolder.revengeImageLayout.setBackgroundColor(RED);
			viewHolder.deleteImageLayout.setBackgroundColor(RED);
			actionIcon.setImageResource(R.drawable.face_lose);
		} 
	}
	private void openChallenge(FriendChallengeEnvelope challenge, boolean proposedByMe){
		if (!challenge.isAccepted()){
			try {
				ServerConnector.acceptChallenge(challenge.getId(), challenge.getOponent().getId());
			} catch (ConnectivityException e) {
				ErrorOccurredDialogUtils dialog = new ErrorOccurredDialogUtils(activity, e);
				dialog.createErrorOccurredPopup();
				e.printStackTrace();
				return;
			}
			challenge.setChallengeStartOponent(SystemConstants.getTime());
		}
		if (proposedByMe && challenge.getChallengeStartProposer()==0){
			try {
				ServerConnector.setChallengeStartTime(challenge.getId());
			} catch (ConnectivityException e) {
				ErrorOccurredDialogUtils dialog = new ErrorOccurredDialogUtils(activity, e);
				dialog.createErrorOccurredPopup();
				e.printStackTrace();
				return;
			}
			challenge.setChallengeStartProposer(SystemConstants.getTime());
		}
		Intent intent = new Intent(activity.getApplicationContext(), FriendChallenge.class);
		intent.putExtra(FriendChallenge.FRIEND_CHALLENGE_ENVELOPE, challenge);
		activity.startActivity(intent);
	}
	private boolean imDoneChallenge(FriendChallengeEnvelope newChallenge) {
		boolean proposedByMe = newChallenge.getProposerFacebookId().equals(MainActivity.userData.getFacebookid());
		if (proposedByMe){
			for (String completed : newChallenge.getImagesPassed().split(StringPool.COMMA)){
				if (completed.equals(StringPool.ZERO)){
					return false;
				}
			}
		}else{
			for (String completed : newChallenge.getImagesOponentPassed().split(StringPool.COMMA)){
				if (completed.equals(StringPool.ZERO)){
					return false;
				}
			}
		}
		return true;
	}
	static class ViewHolder {
		protected LinearLayout layoutBg;
		protected RelativeLayout layoutOverlay;
		protected LinearLayout layoutFriendView;
		protected View challengeView;
		protected ImageView actionIcon;
		protected TextView friendName;
	    protected TextView challengeStart;
	    protected TextView challengeExpires;
	    protected ImageView imgViewer;
	    protected ProgressBar loader;
		protected LinearLayout revengeImageLayout;
    	protected LinearLayout deleteImageLayout;
    }
}